<!--
编辑应用
 -->
<template>
  <div class="app-container paddingT50">
    <div class="paddingLR20 clearfix">
      <el-card shadow="never" class="oper-btn-card">
        <div class="clearfix">
          <div class="fl">
            <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSaveData">保存</el-button>
            <el-button type="default" size="medium" @click="btnCancle">取消</el-button>
          </div>
        </div>
      </el-card>
    </div>
    <el-card shadow="never" class="border-radius-none margin-t2">
      <!-- dataObj: {{ dataObj }} -->
      <el-form
        ref="form"
        :model="formData"
        :rules="rules"
        label-position="right"
        label-width="100px"
        size="mini"
      >
        <h3>基础信息</h3>
        <el-divider/>
        <div class="paddingTb20 w600">
          <el-form-item :label="`应用名称:`" prop="name">
            <el-input v-model="formData.name" maxlength="64" show-word-limit/>
          </el-form-item>
          <el-form-item :label="`APPID:`" prop="appid">
            <el-input v-model="formData.appid" maxlength="40" show-word-limit/>
          </el-form-item>
          <el-form-item :label="`SECRET:`" prop="secret">
            <el-input v-model="formData.secret" maxlength="64" show-word-limit/>
          </el-form-item>
          <el-form-item :label="`应用图标:`">
            <el-upload
              action=""
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :http-request="requestUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon"/>
            </el-upload>
          </el-form-item>
        </div>
      </el-form>
    </el-card>
  </div>
</template>
<script>
import { oftenuse } from '@/libs/mixins'
import { createApplication,updateApplication, findApplicationById } from '@/api/application/application.js'
import { upload } from '../../../api/common/fileupload'

export default {
  name: 'SysApplicationAdd',
  mixins: [oftenuse],
  props: {
    operation: {
      type: String,
      default: null,
      validator: (value) => {
        return ['add', 'update'].indexOf(value) !== -1
      }
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      imageUrl: '',
      appOptions: [],
      appLoading: false,
      appLoad: false,
      formData: {
        appid: null,
        name: null,
        secret: null,
        icon: null
      },
      originDataObj: {}, // 编辑状态初始值，用于对比是否修改
      optionsData: {},
      rules: {
        name: [
          { required: true, message: '请输入应用名称', trigger: 'blur' },
          { min: 1, max: 64, message: '长度在 1 到 64 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {},
  watch: {},
  created() {
    // 页面初始化数据写在这里
    this.initData()
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    //  覆盖默认上传行为
    requestUpload(params) {
      const fileData = new FormData()
      fileData.append('file', params.file)
      fileData.append('FileName', params.file.name)
      fileData.append('async', true)
      upload(fileData).then(res => {
        if (res.data.flag) {
          this.formData.icon = res.data.result.relativePath
          this.imageUrl = URL.createObjectURL(params.file)
        }
      })
    },
    btnSaveData() {
      this.valiData().then(_ => {
        const params = this.formData
        this.setBtnLoading('save', true)
        this.saveData(params).then(_ => {
          this.setBtnLoading('save', false)
        })
      })
    },
    jump2list() {
      console.log(222222)
      this.closeCurrentTag(this.$route)
      this.$router.push({
        name: 'sysApplicationList',
        params: { refresh: true }
      })
    },
    btnCancle() {
      this.jump2list()
    },
    valiData() {
      const v1 = this.handleValid('form')
      return Promise.all([v1])
    },
    saveData(params) {
      this.setBtnLoading('save', true)
      if (!params.id) {
        return createApplication(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '保存异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '保存成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '保存异常！', message: err.message })
        })
      } else {
        return updateApplication(params).then(res => {
          this.setBtnLoading('save', false)
          if (!res.data.flag) {
            this.$notify.error({ title: '修改异常！', message: res.data.message })
            return
          }
          this.$notify.success({ title: '修改成功！' })
          this.jump2list()
        }).catch(err => {
          this.$notify.error({ title: '修改异常！', message: err.message })
        })
      }
    },
    findById(id) {
      findApplicationById({ id: id }).then(res => {
        if (res.data.flag) {
          this.formData = res.data.result
        } else {
          this.$notify.error({ title: '查询失败!', message: res.data.message })
        }
      })
    },
    initData() { // 初始化数据
      console.log('初始化数据')
      this.initOptionsData()
      const id = this.id
      if (id) {
        // 初始化修改时的数据
        this.initUpdateData(id)
      }
    },
    initUpdateData(id) {
      this.findById(id)
    },
    initOptionsData() {
    }
  }
}
</script>

<style scoped>
.el-divider--horizontal {
  margin: 5px 0;
}
</style>
